const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    id: null,
    form: {
      name: '',
      description: '',
      status: 1
    },
    statusIndex: 0,
    statusOptions: ['禁用', '启用'],
    loading: false
  },

  onLoad(options) {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/process-detail/process-detail')) {
      return
    }
    
    if (options.id) {
      this.setData({
        id: options.id
      })
      this.loadData()
    }
  },

  async loadData() {
    try {
      const res = await api.getProcessList({
        id: this.data.id
      })

      if (res.code === 1 && res.data.list.length > 0) {
        const item = res.data.list[0]
        this.setData({
          form: {
            name: item.name,
            description: item.description || '',
            status: item.status
          },
          statusIndex: item.status === 1 ? 1 : 0
        })
      }
    } catch (error) {
      console.error('加载工序详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  onStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value),
      'form.status': parseInt(e.detail.value)
    })
  },

  async onSubmit(e) {
    if (this.data.loading) return

    // 检查权限
    const action = this.data.id ? 'edit' : 'add'
    if (!this.hasPermission('process_manage', action)) {
      wx.showToast({
        title: `您没有${this.data.id ? '编辑' : '新增'}权限`,
        icon: 'none'
      })
      return
    }

    const formData = e.detail.value
    
    if (!formData.name.trim()) {
      wx.showToast({
        title: '请输入工序名称',
        icon: 'none'
      })
      return
    }

    this.setData({ loading: true })

    try {
      const data = {
        name: formData.name.trim(),
        description: formData.description.trim(),
        status: this.data.form.status
      }

      let res
      if (this.data.id) {
        data.id = this.data.id
        res = await api.updateProcess(data)
      } else {
        res = await api.createProcess(data)
      }

      if (res.code === 1) {
        wx.showToast({
          title: this.data.id ? '更新成功' : '创建成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: res.msg || '操作失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('保存工序失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  onCancel() {
    wx.navigateBack()
  },

  // 检查是否有权限执行某个操作
  hasPermission(module, action) {
    // 从session中获取管理员信息
    const app = getApp();
    const adminInfo = app.globalData.adminInfo;
    if (!adminInfo || !adminInfo.id) {
      return false;
    }
    
    // 使用权限工具检查权限（基于管理组）
    return permissionUtils.hasPermission(adminInfo.id, module, action);
  }
})
